package sdk

import (
	"bytes"
	"encoding/json"
	"errors"
	"net/url"
	"strconv"

	"gitee.com/wz-open-platform/wzopen-sdk-go/constants"
	"gitee.com/wz-open-platform/wzopen-sdk-go/model"
	"gitee.com/wz-open-platform/wzopen-sdk-go/tools"
	"github.com/tidwall/gjson"
)

// 获取公司待续费列表
func (c *client) GetCompanyExpireDeviceList(req *model.GetCompanyExpireDeviceListReq) (resp *model.GetCompanyExpireDeviceListResp, err error) {
	method := "GET"
	getparams := url.Values{}
	getparams.Add("page", strconv.Itoa(req.PageModel.Page))
	getparams.Add("limit", strconv.Itoa(req.PageModel.Limit))
	getparams = c.buildGetParam(getparams)
	bytes, err := tools.DoHttp(c.baseURL+"/open/renew/getCompanyExpireDeviceList", method, map[string]string{}, nil, getparams)
	if err != nil {
		return
	}
	if gjson.GetBytes(bytes, "code").Int() != constants.SucceedCode {
		err = errors.New(gjson.GetBytes(bytes, "message").String())
		return
	}
	err = json.Unmarshal(bytes, &resp)
	return
}

// 公司创建续费订单
func (c *client) CreateCompanyRenewOrder(req *model.CreateCompanyRenewOrderReq) (resp *model.CreateCompanyRenewOrderResp, err error) {
	method := "POST"
	postparams := tools.StructToMap(req)
	postparams = c.buildPostParam(postparams)
	postparamBytes, err := json.Marshal(postparams)
	if err != nil {
		return
	}
	bytes, err := tools.DoHttp(c.baseURL+"/open/renew/createCompanyRenewOrder", method, map[string]string{}, bytes.NewBuffer([]byte(postparamBytes)), nil)
	if err != nil {
		return
	}
	if gjson.GetBytes(bytes, "code").Int() != constants.SucceedCode {
		err = errors.New(gjson.GetBytes(bytes, "message").String())
		return
	}
	err = json.Unmarshal(bytes, &resp)
	return
}

// 查询公司续费状态
func (c *client) GetCompanyRenewStatus(req *model.GetCompanyRenewStatusReq) (resp *model.GetCompanyRenewStatusResp, err error) {
	method := "GET"
	getparams := url.Values{}
	getparams.Add("out_trade_no", req.OutTradeNo)
	getparams = c.buildGetParam(getparams)
	bytes, err := tools.DoHttp(c.baseURL+"/open/renew/getCompanyRenewStatus", method, map[string]string{}, nil, getparams)
	if err != nil {
		return
	}
	if gjson.GetBytes(bytes, "code").Int() != constants.SucceedCode {
		err = errors.New(gjson.GetBytes(bytes, "message").String())
		return
	}
	err = json.Unmarshal(bytes, &resp)
	return
}
